var express = require('express');
var router = express.Router();
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");

const IaiClient = tencentcloud.iai.v20200303.Client;

var multiparty = require('multiparty')

var {shopModel,historyModel,boxModel,feedbackModel, userModel,chatModel,MyOrder,Classification, Cate, Saveimg}=require('../model/model')

// 陆珺瑶
router.get('/orderlist', async (req, res) => {})
router.post('/list', async (req, res) => {
  const { page } = req.body;
  const orderlist = await MyOrder.find();
  const shoplist = await shopModel.find().lean().skip((page - 1) * 3).limit(3);
  res.send({
    orderlist,
    shoplist
  })
})


// var router = express.Router();
const app = express();
const httpServer = require('http').createServer(app);
const { Server } = require('socket.io');
let userlist = []
let user_id
const io = new Server(httpServer, {
  cors: {
    // origin: ['http://localhost:3001', 'http://localhost:3002'],
    origin: '*',

    methods: ['GET', 'POST'],
  }
});
// 服务器获取数据库数据
router.get('/getchat', async (req, res) => {

  // 把chatModel数据库的数据的status字段全部改为true
  await chatModel.updateMany({}, { $set: { statu: true } })
  let alllist = await chatModel.find()
  // console.log(alllist, 'alllist');
  res.send({
    code: 200,
    alllist
  })
})
// 获取不在线是的数据
router.get('/getchat1', async (req, res) => {

  // 把chatModel数据库的数据的status字段全部改为true

  let alllist = await chatModel.find()
  // console.log(alllist, 'alllist');
  res.send({
    code: 200,
    alllist
  })
})
// 获取未读消息
router.get('/getunread', async (req, res) => {
  let unread = await chatModel.find({ statu: false })
  // console.log(unread, 'unread');
  res.send({
    code: 200,
    unread
  })
})

// let userlist1 = [...new Set(userlist)]
// 获取到客户端连接
io.on('connection',async (socket) => {
  console.log('socket连接成功', socket.id);
  const useid = socket.handshake.query.user
  console.log(useid, 'useid');
  // if (userlist.length>1) {
  //   socket.emit('chat message', '欢迎来到我们的服务！');
  // }
  // let chatlist = await chatModel.find()
  // if (chatlist.length===0) {
  //   console.log('没有数据');
  //   socket.emit('welcome', '欢迎来到我们的服务！');
  // }
 
  // console.log(useid, 'useid');

  userlist.push(useid)

  userlist = [...new Set(userlist)]
  console.log(userlist, 'list');
  user_id = userlist[1]
  // 断开连接
  socket.on('disconnect', (name, callback) => {
    console.log(userlist, 'list离线');
    console.log(socket.id, '离线');
    userlist = userlist.filter(item => item !== useid)
  })
  // 监听用户的在线情况
  io.emit('online', {
    // 把userlist去重

    // 根据uselist1 里有没有客服，如果没有客服说明客服不在线，提示用户客服在线的时间
    userlist
  
  })

  // 监听客户端发送的消息
  socket.on('message', async (data) => {
    let newdata = JSON.parse(data);
    console.log(newdata, 'newdata、、、、、');
    chatModel.create(newdata)
    // 找到chatmodel中user_id为user_id的数据
    let chatlist = await chatModel.find({ user_id: user_id })

    // let chatlist = await chatModel.find()
    if (chatlist.length===0) {
      console.log('没有数据');
      socket.emit('welcome', '欢迎来到我们的服务！');
    }
    // console.log(chatlist, 'chatlist');
    console.log('客户端发送的消息', newdata);
    // 向客户端发送消息
    // socket.emit('message', newdata);
    socket.broadcast.emit('aaaa', [...chatlist], '服务器向所有客户端发送消息');


  })

})
httpServer.listen(5001, (err) => {
  console.log('服务器启动成功！')
})
// ---------（结束）
router.post('/alllist', async (req, res) => {
  const { id } = req.body;
  const shoplist = await shopModel.find({_id:id});
  res.send({
    shoplist
  })
})

// shop
router.get('/shop', async (req, res) => {
    let { pagenum, pagesize, name } = req.query
    let arr = []
    if (name) {
        let regName = new RegExp(name)
        arr.push({ name: regName })
    }
    if (arr.length != 0) {
        var count = await shopModel.countDocuments({ $and: arr })
        var data = await shopModel.find({ $and: arr })
            .skip((pagenum - 1) * pagesize)
            .limit(pagesize)
    } else {
        var count = await shopModel.countDocuments()
        var data = await shopModel.find()
            .skip((pagenum - 1) * pagesize)
            .limit(pagesize)
    }
    res.send({
        code: 200,
        data: data,
        count: count
    })
});
router.post('/addShop', (req, res) => {
    shopModel.create(req.body)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})



//box
router.get('/box', async (req, res) => {
    let data = await boxModel.find()
    res.send({
        code: 200,
        data: data
    })
})
router.post('/addBox', (req, res) => {
    boxModel.create(req.body)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})



//history
router.get('/history', async (req, res) => {
    let data = await historyModel.find()
    res.send({
        code: 200,
        data: data
    })
})
router.post('/addHistory', (req, res) => {
    historyModel.create(req.body)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})


// 图片上传
router.post('/upload', (req, res) => {
    let form = new multiparty.Form()
    form.uploadDir = 'upload'
    form.parse(req, (err, fields, imgData) => {
        res.send({
            code: 200,
            path: 'http://localhost:3000/' + imgData.file[0].path
        })
    })
})


// feedback
router.post('/addFeedback', (req, res) => {
    feedbackModel.create(req.body)
    res.send({
        code: 200,
        msg: '添加成功'
    })
})

// ----------------------李志杰
router.post('/autoface', (req, res) => {
    let {body}=req.body
    const clientConfig = {
        credential: {
          secretId: "AKIDwoX3LQHv1ua3PYbT8Z4dEhy2sUt57yc2",
          secretKey: "KRK0RegVFqDNJ1GHNOD69A2h9ScbOLDs",
        },
        region: "ap-beijing",
        profile: {
          httpProfile: {
            endpoint: "iai.tencentcloudapi.com",
          },
        },
      };
      // 实例化要请求产品的client对象,clientProfile是可选的
      const client = new IaiClient(clientConfig);
      const params = {
        GroupIds:['20031119'],
        Image:body,
        FaceMatchThreshold:80, //要求的图片检测
        QualityControl:3 //图片的质量控制
      };
      client.SearchFaces(params).then(
        (data) => {
            let flame=data.Results[0].Candidates
            if(flame.length>0){
                res.send({
                    flame:"有"
                })
            }
        },
        (err) => {
            let flame=String(err).split('。')[0].split(":")[1]
            res.send({
                flame:flame
            })
        }
      );
})

router.post('/adduser', (req, res) => {
    userModel.create(req.body)
    res.send({
        code: 200
    })
})

router.post('/authuser', async (req, res) => {
    let { name, password } = req.body
    console.log(name, password)
    let state = await userModel.findOne({ name: name })
    console.log(state)
    if (!state) {
        res.send({
            flame: '没有查找到用户名'
        })
    }else{
        let state2=await userModel.findOne({name:name,password:password})
        if(!state2){
            res.send({
                flame:'密码错误'
            })
        }else{
            res.send({
                flame:"yes"
            })
        }
    }

})

router.post('/addcate', (req, res) => {
    Cate.create(req.body).then(rew => {
        res.send({
            code: 200
        })
    })
})
router.post('/addlist', (req, res) => {
    Classification.create(req.body).then(rew => {
        res.send({
            code: 200,
            message: "添加成功"
        })
    })
})

router.get('/cate', (req, res) => {
    Cate.find().then(data => {
        res.send({
            data
        })
    })
})

router.get('/list', async (req, res) => {
    let { cid, page, pagesize } = req.query
    let arr = []
    if (cid) {
        arr.push({ cid })
    }
    if (arr.length != 0) {
        var data = await Classification.find({ cid: cid }).populate('cid').skip((page - 1) * pagesize).limit(pagesize)
        res.send({
            data
        })
    } else {
        var data = await Classification.find().populate('cid').skip((page - 1) * pagesize).limit(pagesize)
        res.send({
            data
        })
    }
})

router.get('/getlist', (req, res) => {
    Classification.find().then(data => {
        res.send({
            data
        })
    })
})

router.post('/save', (req, res) => {
    Saveimg.create(req.body).then((rew) => {
        res.send({
            code: 200
        })
    })
})

router.get('/savelist', (req, res) => {
    Saveimg.find().then(data => {
        res.send({
            data
        })
    })
})

module.exports = router;
